import axios from "axios";
import qs from "qs";

const request = axios.create({
    timeout: 50000,
    paramsSerializer: function (params) {
        return qs.stringify(params, { indices: false })
    },
});
const authKey = import.meta.env.VITE_APP_USER_AUTH_KEY;
//  给axios添加请求拦截器
request.interceptors.request.use(
    config => {
        //  添加请求头
        config.headers.Authorization = localStorage.getItem(authKey)
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
//  添加响应拦截器
request.interceptors.response.use(
    response => {
        const data = response.data
        console.log("响应数据", data)
        return response.data
    },
    error => {
        console.log('响应错误' ,error)
        //  如果是401，则清空本地的Authorization
        if (error.status === 401) {
            localStorage.removeItem(authKey)
        }
        return Promise.reject(error)
    }
)

const get = (url,  params) => {
    return request.get(url, params)
}
const post = (url, params) => {
    return request.post(url, params)
}
const put = (url, params) => {
    return request.put(url, params)
}
const deletes = (url, params) => {
    return request.delete(url, params)
}

export default {
    get,
    post,
    put,
    delete: deletes,
    req: request
}
